<template>
  <div>
    <el-dialog
      :fullscreen="true"
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="100%"
      :before-close="handleClose">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-form-inline" :inline="true">
        <el-row>
          <el-col :span="6" class="center">
            <el-form-item label="" prop="imageUrl">
              <el-upload
                class="avatar-uploader"
                :action="`${baseUrl}/employee/v1/uploadPhoto`"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                name="picture"
                 v-model="ruleForm.imageUrl">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="人员编号" prop="employeeNo">
              <el-input v-model.trim="ruleForm.employeeNo"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="姓名" prop="employeeName">
              <el-input v-model.trim="ruleForm.employeeName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="ruleForm.gender" placeholder="请选择">
                <el-option v-for="item in sexList" :key="item.key" :label="item.value" :value="item.key"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="婚姻状态" prop="maritalStatus">
              <el-select v-model="ruleForm.maritalStatus" placeholder="请选择">
                <el-option v-for="item in maritalList" :key="item.key" :label="item.value" :value="item.key"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="民族" prop="ethnic">
              <el-input v-model.trim="ruleForm.ethnic"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="政治面貌" prop="politicalStatus">
              <el-select v-model="ruleForm.politicalStatus" placeholder="请选择">
                <el-option v-for="item in politicsList" :key="item.key" :label="item.value" :value="item.key"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="出生日期" prop="birthday">
              <el-date-picker :picker-options="pickerOptions" default-value value-format="yyyy-MM-dd" :editable='false' type="date" placeholder="选择日期" v-model="ruleForm.birthday" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="年龄">
              <el-input disabled :value="getAge(ruleForm.birthday)"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="家庭住址" prop="address">
              <el-input v-model="ruleForm.address"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="籍贯" prop="residency">
              <el-input v-model="ruleForm.residency"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="手机号码" prop="phoneNum">
              <el-input v-model="ruleForm.phoneNum"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="ruleForm.email"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="身份证号码" prop="idNum">
              <el-input v-model="ruleForm.idNum"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="身高" prop="height">
              <el-col :span="20">
                <el-input v-model="ruleForm.height"></el-input>
              </el-col>
              <el-col :span="4">
                <span>cm</span>
              </el-col>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="体重" prop="weight">
              <el-col :span="20">
                <el-input v-model="ruleForm.weight"></el-input>
              </el-col>
              <el-col :span="4">
                <span>kg</span>
              </el-col>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="紧急联系人" prop="emergencyContactPerson">
              <el-input v-model="ruleForm.emergencyContactPerson"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="紧急联系电话" prop="emergencyContactNumber" label-width="110px">
              <el-input v-model="ruleForm.emergencyContactNumber"></el-input>
            </el-form-item>
          </el-col>

        </el-row>

        <hr>
        <el-row class="mt-20">
          <el-col :span="6">
            <el-form-item label="毕业院校" prop="graduatedFrom">
              <el-input v-model="ruleForm.graduatedFrom"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="学历" prop="highestEducation">
              <el-select v-model="ruleForm.highestEducation" placeholder="请选择">
                <el-option v-for="item in educationList" :key="item.key" :label="item.value" :value="item.key"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="专业" prop="major">
              <el-input v-model="ruleForm.major"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="毕业时间" prop="graduatedDate">
              <el-date-picker :picker-options="pickerOptions" default-value value-format="yyyy-MM-dd" :editable='false' type="date" placeholder="选择日期" v-model="ruleForm.graduatedDate" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="6">
            <el-form-item label="部门" prop="departmentId" v-if="true">
              <el-cascader
                :show-all-levels="false"
                :options="departmentList"
                @active-item-change="handleItemChange"
                :props="props"
                v-model="ruleForm.departmentId" :placeholder="cascaderPlace"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="雇佣性质" prop="employType">
              <el-select v-model="ruleForm.employType" placeholder="请选择">
                <el-option v-for="item in employmentList" :key="item.key" :label="item.value" :value="item.key"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否转正" prop="isRegular">
              <el-select v-model="ruleForm.isRegular" placeholder="请选择" @change="isRegularChange">
                <el-option v-for="item in isProbationList" :key="item.key" :label="item.value" :value="item.key"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="转正日期" prop="regularDate">
              <el-date-picker :disabled="regularDateDisable" :picker-options="pickerOptions" default-value value-format="yyyy-MM-dd" :editable='false' type="date" placeholder="选择日期" v-model="ruleForm.regularDate" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="进公司时间" prop="onBoardDate">
              <el-date-picker :picker-options="pickerOptions" default-value value-format="yyyy-MM-dd" :editable='false' type="date" placeholder="选择日期" v-model="ruleForm.onBoardDate" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="参加工作时间" prop="workDate" label-width="110px">
              <el-date-picker :picker-options="pickerOptions" default-value value-format="yyyy-MM-dd" :editable='false' type="date" placeholder="选择日期" v-model="ruleForm.workDate" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工龄">
              <el-input disabled :value="getAge(ruleForm.onBoardDate)"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="doSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {baseUrl} from '@/constants/config'
import { findEmpParentDept,findEmpChildrenDept,addEmployee,updateEmployee,findEmployee,uploadPhoto } from "@/api/departPersonManage/personnelFiles";
import {
  estateId,
  employmentList,
  sexList,
  maritalList,
  politicsList,
  educationList,
  isProbationList
} from "@/constants/code";
import {
  employeeNoInput,
  idNumInput,
  emailInput,
  phoneNumInput,
  ageInputN,
  requireInput,
  requireInputWithMaxLength,
  requireInputWithMaxLengthN
} from "@/utils/validateForm";
import getAge from "@/utils/getAge";
import "@/utils/toDate";

export default {
  data() {
    return {
      baseUrl,
      cascaderPlace: '请选择',
      picture: '',
      imageUrl: "",
      ruleForm: {
        photo: '',
        employeeNo: "",
        employeeName: "",
        gender: "",
        maritalStatus: "",
        ethnic: "",
        politicalStatus: "",
        birthday: "",
        address: "",
        residency: "",
        phoneNum: "",
        email: "",
        idNum: "",
        height: "",
        weight: "",
        emergencyContactPerson: "",
        emergencyContactNumber: "",
        graduatedFrom: "",
        highestEducation: "",
        major: "",
        graduatedDate: "",
        // departmentId: "2784949974893568",
        departmentId: [],
        employType: "",
        isRegular: "",
        regularDate: "",
        onBoardDate: "",
        workDate: ""
      },
      rules: {
        employeeNo: employeeNoInput,
        employeeName: requireInputWithMaxLength("请输入"),
        gender: requireInput("请选择", "change"),
        maritalStatus: requireInput("请选择", "change"),
        ethnic: requireInputWithMaxLength("请输入"),
        politicalStatus: requireInput("请选择", "change"),
        birthday: requireInput("请选择", "change"),
        address: requireInputWithMaxLength("请输入"),
        residency: requireInputWithMaxLength("请输入"),
        phoneNum: phoneNumInput,
        email: emailInput,
        idNum: idNumInput,
        emergencyContactPerson: requireInputWithMaxLength("请输入"),
        emergencyContactNumber: phoneNumInput,
        highestEducation: requireInput("请选择", "change"),
        departmentId: requireInput("请选择", "change"),
        employType: requireInput("请选择", "change"),
        isRegular: requireInput("请选择", "change"),
        onBoardDate: requireInput("请选择", "change"),
        workDate: requireInput("请选择", "change"),
      },
      dialogVisible: true,
      dialogTitle: this.$route.params.id!='0' ? "编辑人员档案" : "新增人员档案",
      employmentList,
      sexList,
      maritalList,
      politicsList,
      educationList,
      isProbationList,
      getAge,

      pickerOptions: {
        disabledDate(time) {
          return (
            time.getTime() > new Date().getTime()
          );
        }
      },
      departmentList: [],
      props: {
        label: 'departmentName',
        value: 'departmentId',
        children: 'zones'
      },
      count: 0,
      regularDateDisable: true,
    };
  },

  created() {
    this.findEmpParentDeptAsync();
    if(this.$route.params.id!='0') {
      this.findEmployeeAsync()
    }
  },

  methods: {
    handleClose() {
      this.$router.go(-1);
    },

    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.ruleForm.photo = res.data.photoId;
      this.picture = res.data.file;
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
        return isJPG
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return isLt2M
      }
      this.picture = file;
      console.log(this.picture);
      //return isJPG && isLt2M;
    },

    isRegularChange(val) {
      this.regularDateDisable = val!=1
    },

    doSubmit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          let fn = this.dialogTitle=='编辑人员档案' ? this.updateEmployeeAsync : this.addEmployeeAsync
          fn();
        }
      });
    },

    async handleItemChange(val) {
      let _departmentId = val[val.length-1];
      let {code,data,msg} = await findEmpChildrenDept({
        departmentId: _departmentId
      });
      if(code=='00000') {
        let _data = data.map(item=> {
          if(item.hasChild) {
            item.zones = [];
          }
          return item
        });

        let recursion = (list)=> {
          list.forEach((item,index,arr) => {
            if(item.departmentId == _departmentId) {
              if(arr[index].hasOwnProperty('zones')) {
                arr[index].zones = _data;
              }
            }else{
              if(item.hasOwnProperty('zones')) {
                recursion(item.zones);
              }
            }
          })
        }
        recursion(this.departmentList)

      }
    },


    async findEmpParentDeptAsync() {
      let {code,data,msg} = await findEmpParentDept();
      if(code=='00000') {
        this.departmentList = data.map(item=> {
          if(item.hasChild) {
            item.zones = [];
          }
          return item;
        });
      }
    },

    async addEmployeeAsync() {
      let form = {...this.ruleForm};
      form.departmentId = this.ruleForm.departmentId[this.ruleForm.departmentId.length-1]

      let {code,data,msg} = await addEmployee(form);
      if(code=='00000') {
        this.$router.go(-1);
      }
    },

    async updateEmployeeAsync() {
      let form = {...this.ruleForm};
      form.departmentId = this.ruleForm.departmentId[this.ruleForm.departmentId.length-1]

      let {code,data,msg} = await updateEmployee({employeeId:this.$route.params.id,...form});
      if(code=='00000') {
        this.$router.go(-1);
      }
    },

    async findEmployeeAsync() {
      let {code,data,msg} = await findEmployee({
        employeeId:this.$route.params.id
      });
      if(code=='00000') {
        for(let i in data) {
          if(this.ruleForm.hasOwnProperty(i)) {
            this.ruleForm[i] = data[i];
          }
        }
        let keys = ['birthday','graduatedDate','regularDate','onBoardDate','workDate'];
        for(let i of keys) {
          this.ruleForm[i] = new Date(this.ruleForm[i]).Format('yyyy-MM-dd');
        }
        this.ruleForm.departmentId = [this.ruleForm.departmentId];
        this.cascaderPlace = data.departmentName;
        this.regularDateDisable = this.ruleForm.isRegular != 1;
        this.imageUrl = this.ruleForm.photo;
      }
    },

    async uploadPhotoAsync() {

    }

  }
};
</script>

<style>
.center {
  text-align: center;
}
.avatar-uploaderP {
  display: inline;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background-color: #efefef;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 170px;
  height: 170px;
  line-height: 170px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
